package com.xiaoming.e3mall.cart.controller;

import com.xiaoming.e3mall.CartService;
import com.xiaoming.e3mall.common.utils.CookieUtils;
import com.xiaoming.e3mall.common.utils.E3Result;
import com.xiaoming.e3mall.common.utils.JsonUtils;
import com.xiaoming.e3mall.pojo.TbItem;
import com.xiaoming.e3mall.pojo.TbUser;
import com.xiaoming.e3mall.service.ItemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物车处理Controller
 */

@Controller
public class CartController {

    @Value("${COOKIE_CART_EXPIRE}")
    private Integer COOKIE_CART_EXPIRE;

    @Autowired
    private ItemService itemService;
    @Autowired
    private CartService cartService;

    @RequestMapping("/cart/add/{itemId}")
    public String addCart(@PathVariable Long itemId, @RequestParam(defaultValue = "1") Integer num,
                          HttpServletRequest request, HttpServletResponse response) {

        //加入了全局的拦截器判断用户是否登录
        TbUser user = (TbUser) request.getAttribute("user");
        //如果登录了就将数据写入reids中
        if(user !=null){
            //保存到redis中
            cartService.addCart(user.getId(), itemId, num);
            //返回逻辑视图
            return "cartSuccess.jsp";
        }
        //如果没有登录就将数据写在客户端(cookie)
        //从cookie中取购物车列表
        List<TbItem> cartList = getCartListFromCookie(request);
        Boolean flag = false;
        //判断商品在商品列表中是否存在
        for (TbItem tbItem : cartList) {
            //存在 数量+num
            if (tbItem.getId() == itemId.longValue()) {
                flag = true;
                //找到商品 数量相加
                tbItem.setNum(tbItem.getNum() + num);
                //跳出循环
                break;
            }
        }
        //不存在,从根据id从数据库中查询 --> TbItem对象
        if (!flag) {
            TbItem item = itemService.getItemById(itemId);
            //设置商品数量
            item.setNum(num);
            //取一张图片显示
            String image = item.getImage();
            if (StringUtils.isNotBlank(image))
                item.setImage(image.split(",")[0]);

            //将商品添加到商品列表
            cartList.add(item);
        }

        //写入cookie
        CookieUtils.setCookie(request, response, "cart", JsonUtils.objectToJson(cartList),
                COOKIE_CART_EXPIRE, true);
        //返回成功页面
        return "cartSuccess.jsp";

    }


    /**
     * 从cookie中取购物车列表
     */
    public List<TbItem> getCartListFromCookie(HttpServletRequest request) {
        String json = CookieUtils.getCookieValue(request, "cart", "utf-8");
        //判断json是否为空
        if (StringUtils.isBlank(json))
            return new ArrayList<>();
        //把json转成商品列表
        List<TbItem> itemList = JsonUtils.jsonToList(json, TbItem.class);
        return itemList;
    }


    /**
     * 展示购物车列表
     */
    @RequestMapping("/cart/cart")
    public String showCartList(HttpServletRequest request,HttpServletResponse response) {
        List<TbItem> cartList = getCartListFromCookie(request);
        //判断用户是否登录
        TbUser user = (TbUser) request.getAttribute("user");
        //如果登录 将cookie跟reids合并
        if(user != null){
            cartService.mergeCart(user.getId(), cartList);
            //把cookie中的购物车删除
            CookieUtils.deleteCookie(request, response, "cart");
            //从服务端取购物车列表
            cartList = cartService.getCartList(user.getId());
        }
        //如果没有登录 查找cookie中的
        //把列表传递给页面
        request.setAttribute("cartList", cartList);
        //返回逻辑视图
        return "cart.jsp";
    }

    /**
     * 更新购物车商品数量
     */
    @RequestMapping("/cart/update/num/{itemId}/{num}")
    @ResponseBody
    public E3Result updateCartNum(@PathVariable Long itemId, @PathVariable Integer num,
                                  HttpServletRequest request, HttpServletResponse response) {

        //判断是否登录
        TbUser user = (TbUser) request.getAttribute("user");

        if(user!=null){
            cartService.updateCartNum(user.getId(), itemId, num);
            return E3Result.ok();
        }

        //从cookie中取购物车列表
        List<TbItem> cartList = getCartListFromCookie(request);
        //遍历购物车列表找到对应的商品
        for (TbItem item : cartList) {
            if (item.getId() == itemId.longValue()) {
                //更新数量
                item.setNum(num);
                break;
            }
        }
        //将购物车列表写会cookie
        CookieUtils.setCookie(request, response, "cart", JsonUtils.objectToJson(cartList),
                COOKIE_CART_EXPIRE, true);

        //返回(这里随便返回就行)
        return E3Result.ok();
    }


    /**
     * 删除购物车商品
     */
    @RequestMapping("/cart/delete/{itemId}")
    public String deleteCartItem(@PathVariable Long itemId, HttpServletRequest request,
                                 HttpServletResponse response) {
        //判断用户是否为登录状态
        TbUser user = (TbUser) request.getAttribute("user");
        if (user != null) {
            cartService.deleteCartItem(user.getId(), itemId);
            return "redirect:/cart/cart.html";
        }
        //从cookie中取购物车列表
        List<TbItem> cartList = getCartListFromCookie(request);
        //遍历列表，找到要删除的商品
        for (TbItem tbItem : cartList) {
            if (tbItem.getId().longValue() == itemId) {
                //删除商品
                cartList.remove(tbItem);
                //跳出循环,否则会报错(只适用于单个元素删除)
                break;
            }
        }
        //把购物车列表写入cookie
        CookieUtils.setCookie(request, response, "cart", JsonUtils.objectToJson(cartList), COOKIE_CART_EXPIRE, true);
        //返回逻辑视图
        return "redirect:/cart/cart.html";
    }


}
